from django.conf import settings
from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import User

import re

from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_verify_email

from django.core.mail import send_mail

from itsdangerous import TimedJSONWebSignatureSerializer as TJS

class UserSerializer(serializers.ModelSerializer):

    # 显示模型类中没有的字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)

    token = serializers.CharField(read_only=True)

    class Meta:

        model = User
        fields = ('username','mobile','password','password2','allow','sms_code','id','token')

        extra_kwargs = {
            'password':{
                'max_length':20,
                'min_length':8,
                'write_only':True,
            },
            'username':{
                'max_length': 20,
                'min_length': 5,

            }
        }

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机格式错误')
        return value

    # 验证勾选中状态
    def validated_allow(self,value):
        if not value:
            raise serializers.ValidationError('请同意协议')
        return value

    # 验证两次密码和短信验证
    def validate(self, attrs):

        # 判断两次密码是否相同
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('两次输入的密码不同')

        # 判断短信验证码是否相同
        redis_coon = get_redis_connection('verify')
        mobile = attrs['mobile']
        real_sms_code = redis_coon.get('sms_%s'%mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    # 保存数据
    def create(self, validated_data):
        '''创建用户'''
        # 移除数据库模型类中不存在的属性
        # del validated_data['password2']
        # del validated_data['sms_code']
        # del validated_data['allow']
        # user = super().create(validated_data)

        user = User.objects.create_user(username=validated_data['username'],password=validated_data['password'],
                                        mobile=validated_data['mobile'])

        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 生成jwk token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    '''
        用户详细信息序列化器
    '''
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmailSerializer(serializers.Serializer):
    '''
        邮箱序列化器
    '''
    email = serializers.EmailField()

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email':{
                'required':True,
            }
        }

    def update(self, instance, validated_data):
        '''保存邮箱'''
        # 加密用户数据
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'username':instance.username}).decode()


        # 收件人
        to_email = validated_data['email']
        # 异步发送邮件
        send_verify_email.delay(token,to_email)

        instance.email = validated_data['email']

        instance.save()

        return instance
